﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;
using Qplus.Commands;
using Qplus.beans;
using Newtonsoft.Json.Linq;
using Qplus.Infrastructure;

namespace Qplus.UI
{
    public partial class SearchFriends : PhoneApplicationPage
    {
        List<FriendControl> fList = new List<FriendControl>();
        public SearchFriends()
        {
            InitializeComponent();

            //recommendListTest();
            //createRecommendList();
            //rlist.ItemsSource = fList;

            //searchListTest();
            this.searchCtrl.checkBtnEx.Click += new RoutedEventHandler(checkBtnEx_Click);
            //createSearchLst();

            //onlineListTest();
            //createOnlineList();

        }
        bool test = false;
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (test)
            {
                GetChatListCommand ChatCommand = new GetChatListCommand(QplusT.Instance.getUser().userID.ToString(), System.Text.Encoding.UTF8.GetString(QplusT.Instance.getUser().key, 0, QplusT.Instance.getUser().key.Length));
                ChatCommand.GetChatListCommandReceivedFromHttpServer += new EventHandler<MessageReceivedFromServer>(GetChatListCommand_MessageReceivedFromHttpServer);
                ChatCommand.execute(QplusT.Instance.getUser().url);
            }

            GetUserListCommand UserList_1_Command = new GetUserListCommand(QplusT.Instance.getUser().userID, QplusT.Instance.getUser().key);
            UserList_1_Command.GetUserList_1_CommandReceivedFromHttpServer += new EventHandler<MessageReceivedFromServer>(command_GetUserList_1_CommandReceivedFromHttpServer);
            UserList_1_Command.set(1);
            UserList_1_Command.execute(QplusT.Instance.getUser().url);

            GetUserListCommand UserList_2_Command = new GetUserListCommand(QplusT.Instance.getUser().userID, QplusT.Instance.getUser().key);
            UserList_2_Command.GetUserList_2_CommandReceivedFromHttpServer += new EventHandler<MessageReceivedFromServer>(command_GetUserList_2_CommandReceivedFromHttpServer);
            UserList_2_Command.set(2);
            UserList_2_Command.execute(QplusT.Instance.getUser().url);
            #region
            //user[] friendList;
            //System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.TryGetValue<user[]>("userList", out friendList);
            //l2cInfo l2c;
            //System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.TryGetValue<l2cInfo>("l2cInfo", out l2c);
            //for (int i = 0; i < friendList.Length; i++)
            //{
            //    //Qplus.Commands.GetResCommand command_GetRes = new Qplus.Commands.GetResCommand(
            //    //    friendList.userList[i].userID.ToString(),
            //    //    friendList.userList[i].headValue);
            //    //command_GetRes.set(friendList.userList[i].headValue);
            //    //command_GetRes.execute(l2c.UpgradeURL);
            //    //Qplus.beans.Session session = new Qplus.beans.Session();
            //    //Qplus.Commands.GetFileCommand command_GetFile = new Qplus.Commands.GetFileCommand(
            //    //    l2c.UserID.ToString(), 
            //    //    System.Text.Encoding.UTF8.GetString(l2c.Key, 0, l2c.Key.Length),
            //    //    session,
            //    //    (long)friendList.userList[i].headType,
            //    //    friendList.userList[i].headValue);
            //    //command_GetFile.set(friendList.userList[i].headValue);
            //    //command_GetFile.execute(l2c.UpgradeURL);
            //    fList.Add(new FriendControl()
            //    {
            //        CtrlType=friendCtrlTypeEnum.stranger,
            //        UserID = friendList[i].userID,
            //        UserName = friendList[i].userName,
            //        UserLevel = friendList[i].userLevel,
            //        HeadType = friendList[i].headType,
            //        HeadValue = friendList[i].headValue
            //    });
            //}
            #endregion
            base.OnNavigatedTo(e);
        }
#region 推荐
        void GetChatListCommand_MessageReceivedFromHttpServer(object sender, MessageReceivedFromServer e)
        {
            SearchData.Instance.ChatList = JArray.Parse(e.strMessage);
            //Dispatcher.BeginInvoke(() => { recommendWP.Children.Clear(); });
            createRecommendList();
        }
        void command_GetUserList_1_CommandReceivedFromHttpServer(object sender, MessageReceivedFromServer e)
        {
            SearchData.Instance.UserList1 = JObject.Parse(e.strMessage);
            //Dispatcher.BeginInvoke(() => { recommendWP.Children.Clear(); });
            createRecommendList();
        }
        public LinkedList<FriendControl> recommendLklst = new LinkedList<FriendControl>();
        public bool createRecommendList()
        {
/*            var node = SearchData.Instance.ChatList.First;
            int count = SearchData.Instance.ChatList.Count;
            while (null != node)
            {
                FriendControl frd = new FriendControl()
                {
                    CtrlType = friendCtrlTypeEnum.stranger,
                    Type = (int)node["peerType"],
                    UserID = (int)node["peerID"],
                    UserName = (string)node["peerName"],
                    UserLevel = (string)node["peerLevel"],
                    HeadType = (int)node["headType"],
                    HeadValue = (string)node["headValue"]
                };
                onlineWP.Children.Add(frd);
                node = node.Next;
            }*/
            var node = SearchData.Instance.UserList1["userList"].First;
            int count = SearchData.Instance.UserList1["userList"].Count();
            recommendCount.Text = count.ToString();
            while (null != node)
            {
                FriendControl frd = new FriendControl()
                {
                    UserID = (int)node["userID"],
                    UserName = (string)node["userName"],
                    UserLevel = (string)node["userLevel"],
                    HeadType = (int)node["headType"],
                    HeadValue = (string)node["headValue"],
                    CtrlType = friendCtrlTypeEnum.stranger,
                };
                recommendWP.Children.Add(frd);
                node = node.Next;
            }
            return true;
        }
#endregion

#region 搜索
        public LinkedList<FriendControl> searchLklst = new LinkedList<FriendControl>();

        void checkBtnEx_Click(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
            SearchFriendCommand command = new SearchFriendCommand(QUser.Instance.userID, QUser.Instance.key);
            command.set(searchCtrl.UserName, searchCtrl.Age, searchCtrl.Sex, 0);
            command.execute(QUser.Instance.url);
            command.SearchFriendCommandReceivedFromHttpServer += new EventHandler<Infrastructure.MessageReceivedFromServer>(command_SearchFriendCommandReceivedFromHttpServer);
        }

        void command_SearchFriendCommandReceivedFromHttpServer(object sender, Infrastructure.MessageReceivedFromServer e)
        {
            //throw new NotImplementedException();
            JObject jo=JObject.Parse(e.strMessage);
            var node = jo["userList"].First;
            while (null != node)
            {
                FriendControl frd = new FriendControl()
                {
                    UserID = (int)node["userID"],
                    UserName = (string)node["userName"],
                    UserLevel = (string)node["userLevel"],
                    HeadType = (int)node["headType"],
                    HeadValue = (string)node["headValue"],
                    CtrlType = friendCtrlTypeEnum.stranger,
                };
                searchWP.Children.Add(frd);
                node = node.Next;
            }
        }
#endregion

#region 在线
        void command_GetUserList_2_CommandReceivedFromHttpServer(object sender, MessageReceivedFromServer e)
        {
            SearchData.Instance.UserList2 = JObject.Parse(e.strMessage);
            //Dispatcher.BeginInvoke(() => { onlineWP.Children.Clear(); });
            createOnlineList();
        }
        public LinkedList<FriendControl> onlineLklst = new LinkedList<FriendControl>();
        public bool createOnlineList()
        {
            var node = SearchData.Instance.UserList2["userList"].First;
            int count = SearchData.Instance.UserList2.Count;
            onlineCount.Text = count.ToString();
            while (null != node)
            {
                FriendControl frd = new FriendControl()
                {
                    CtrlType = friendCtrlTypeEnum.stranger,
                    UserID = (int)node["userID"],
                    UserName = (string)node["userName"],
                    UserLevel = (string)node["userLevel"],
                    HeadType = (int)node["headType"],
                    HeadValue = (string)node["headValue"]
                };
                onlineWP.Children.Add(frd);
                node = node.Next;
            }
            return true;
        }
#endregion

        /*private void recommendFriendsCreate(int StrangerNum)
        {
            int buttonNumber = StrangerNum;
            Random ra = new Random();

            Border[] bdrArray = new Border[buttonNumber];
            ButtonEx[] btnExArray = new ButtonEx[buttonNumber];
            for (int i = 0; i < buttonNumber; i++)
            {
                bdrArray[i] = new Border()
                {
                    Margin = new Thickness(20),
                    Background = new SolidColorBrush(new Color() { A = byte.Parse((ra.Next(255)).ToString()), R = byte.Parse((ra.Next(255)).ToString()), G = byte.Parse((ra.Next(255)).ToString()), B = byte.Parse((ra.Next(255)).ToString()) })
                };
                ImageBrush imgBrh = new ImageBrush()
                {
                    ImageSource = new BitmapImage(new Uri("/Qplus;component/Pic/icon_userhand_def.png", UriKind.RelativeOrAbsolute)),
                    Stretch = Stretch.None
                };

                btnExArray[i] = new ButtonEx()
                {
                    Content = "Stranger" + i.ToString(),
                    VerticalContentAlignment = System.Windows.VerticalAlignment.Bottom,

                    PressedBorderBrush = new SolidColorBrush(new Color() { A = 0xff, R = 173, G = 216, B = 230 }),
                    BorderBrush = new SolidColorBrush(Colors.Transparent),
                    BorderThickness = new Thickness(8),
                    //Style = (Style)App.Current.Resources["buttonExStyle"],
                    Background = imgBrh,
                    PressedBackground = imgBrh
                };
                //btnExArray[i].Background = new SolidColorBrush(Colors.Blue);
                //btnExArray[i].BorderBrush = new SolidColorBrush(Colors.Yellow);
                //btnArray[i].Foreground = new SolidColorBrush(Colors.Red);
                btnExArray[i].Click += userInfo;
                //btnExArray[i].GotFocus += searchFriendsBtn_GotFocus;
                //btnExArray[i].LostFocus += searchFriendsBtn_LostFocus;
                //btnArray[i].Hold += searchFriendsBtn_Press;
                //btnArray[i].KeyDown += searchFriendsBtn_Press;
                //};
                Grid.SetColumn(bdrArray[i], i % 2);
                Grid.SetRow(bdrArray[i], i / 2);
                Grid.SetColumn(btnExArray[i], i % 2);
                Grid.SetRow(btnExArray[i], i / 2);
                RowDefinition rowDef = new RowDefinition();
                rowDef.Height = new GridLength(200);
                recommendGrid.RowDefinitions.Add(rowDef);
                recommendGrid.Children.Add(bdrArray[i]);
                recommendGrid.Children.Add(btnExArray[i]);
            }
        }

        private void onlineFriendsCreate(int StrangerNum)
        {
            int buttonNumber = StrangerNum;
            Random ra = new Random();

            Border[] bdrArray = new Border[buttonNumber];
            ButtonEx[] btnExArray = new ButtonEx[buttonNumber];
            for (int i = 0; i < buttonNumber; i++)
            {
                bdrArray[i] = new Border()
                {
                    Margin = new Thickness(20),
                    Background = new SolidColorBrush(new Color() { A = byte.Parse((ra.Next(255)).ToString()), R = byte.Parse((ra.Next(255)).ToString()), G = byte.Parse((ra.Next(255)).ToString()), B = byte.Parse((ra.Next(255)).ToString()) })
                };
                ImageBrush imgBrh = new ImageBrush()
                {
                    ImageSource = new BitmapImage(new Uri("/Qplus;component/Pic/icon_userhand_def.png", UriKind.RelativeOrAbsolute)),
                    Stretch = Stretch.None
                };

                btnExArray[i] = new ButtonEx()
                {
                    Content = "Stranger" + i.ToString(),
                    VerticalContentAlignment = System.Windows.VerticalAlignment.Bottom,

                    PressedBorderBrush = new SolidColorBrush(new Color() { A = 0xff, R = 173, G = 216, B = 230 }),
                    BorderBrush = new SolidColorBrush(Colors.Transparent),
                    BorderThickness = new Thickness(8),
                    //Style = (Style)App.Current.Resources["buttonExStyle"],
                    Background = imgBrh,
                    PressedBackground = imgBrh
                };
                //btnExArray[i].Background = new SolidColorBrush(Colors.Blue);
                //btnExArray[i].BorderBrush = new SolidColorBrush(Colors.Yellow);
                //btnArray[i].Foreground = new SolidColorBrush(Colors.Red);
                btnExArray[i].Click += userInfo;
                //btnExArray[i].GotFocus += searchFriendsBtn_GotFocus;
                //btnExArray[i].LostFocus += searchFriendsBtn_LostFocus;
                //btnArray[i].Hold += searchFriendsBtn_Press;
                //btnArray[i].KeyDown += searchFriendsBtn_Press;
                //};
                Grid.SetColumn(bdrArray[i], i % 2);
                Grid.SetRow(bdrArray[i], i / 2);
                Grid.SetColumn(btnExArray[i], i % 2);
                Grid.SetRow(btnExArray[i], i / 2);
                RowDefinition rowDef = new RowDefinition();
                rowDef.Height = new GridLength(200);
                onlineGrid.RowDefinitions.Add(rowDef);
                onlineGrid.Children.Add(bdrArray[i]);
                onlineGrid.Children.Add(btnExArray[i]);
            }
        }*/

        private void userInfo(object sender, RoutedEventArgs e)
        {
            PopupContainer pc = new PopupContainer(this);
            PopupUserInfo popupUserInfo = new PopupUserInfo();
            popupUserInfo.starChatBtnEx.Click += starChatBtnEx_Click;
            popupUserInfo.starChatBtnEx.Visibility = System.Windows.Visibility.Visible;
            pc.Show(popupUserInfo);
        }
        private void starChatBtnEx_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/UI/Chat.xaml", UriKind.Relative));
        }
        private void refreshBtn_Click(object sender, RoutedEventArgs e)
        {

        }

        #region TEST
        private void recommendListTest()
        {
            FriendControl stranger1 = new FriendControl()
            {
                UserID = 1,
                UserName = "陌生人1",
                CtrlType = friendCtrlTypeEnum.stranger,
                //CtrlBackGround = new SolidColorBrush(Colors.Red),
                //BtnExBackGround = new ImageBrush() { ImageSource = new BitmapImage(new Uri("/Qplus;component/Pic/icon_search_friends_item.png", UriKind.RelativeOrAbsolute)) }
            };
            FriendControl stranger2 = new FriendControl()
            {
                UserID = 2,
                UserName = "陌生人2",
                CtrlType = friendCtrlTypeEnum.stranger,
                //CtrlBackGround = new SolidColorBrush(Colors.Red),
                //BtnExBackGround = new ImageBrush() { ImageSource = new BitmapImage(new Uri("/Qplus;component/Pic/icon_search_friends_item.png", UriKind.RelativeOrAbsolute)) }
            };
            FriendControl stranger3 = new FriendControl()
            {
                UserID = 3,
                UserName = "陌生人3",
                CtrlType = friendCtrlTypeEnum.stranger,
                //CtrlBackGround = new SolidColorBrush(Colors.Red),
                //BtnExBackGround = new ImageBrush() { ImageSource = new BitmapImage(new Uri("/Qplus;component/Pic/icon_search_friends_item.png", UriKind.RelativeOrAbsolute)) }
            };
            FriendControl stranger4 = new FriendControl()
            {
                UserID = 4,
                UserName = "陌生人4",
                CtrlType = friendCtrlTypeEnum.stranger,
                //CtrlBackGround = new SolidColorBrush(Colors.Red),
                //BtnExBackGround = new ImageBrush() { ImageSource = new BitmapImage(new Uri("/Qplus;component/Pic/icon_search_friends_item.png", UriKind.RelativeOrAbsolute)) }
            };
            recommendLklst.AddLast(stranger1);
            recommendLklst.AddLast(stranger2);
            recommendLklst.AddLast(stranger3);
            recommendLklst.AddLast(stranger4);
        }
        private void searchListTest()
        {
            FriendControl stranger1 = new FriendControl()
            {
                UserID = 1,
                UserName = "陌生人1",
                CtrlType = friendCtrlTypeEnum.stranger,
                //CtrlBackGround = new SolidColorBrush(Colors.Red),
                //BtnExBackGround = new ImageBrush() { ImageSource = new BitmapImage(new Uri("/Qplus;component/Pic/icon_search_friends_item.png", UriKind.RelativeOrAbsolute)) }
            };
            FriendControl stranger2 = new FriendControl()
            {
                UserID = 2,
                UserName = "陌生人2",
                CtrlType = friendCtrlTypeEnum.stranger,
                //CtrlBackGround = new SolidColorBrush(Colors.Red),
                //BtnExBackGround = new ImageBrush() { ImageSource = new BitmapImage(new Uri("/Qplus;component/Pic/icon_search_friends_item.png", UriKind.RelativeOrAbsolute)) }
            };
            FriendControl stranger3 = new FriendControl()
            {
                UserID = 3,
                UserName = "陌生人3",
                CtrlType = friendCtrlTypeEnum.stranger,
                //CtrlBackGround = new SolidColorBrush(Colors.Red),
                //BtnExBackGround = new ImageBrush() { ImageSource = new BitmapImage(new Uri("/Qplus;component/Pic/icon_search_friends_item.png", UriKind.RelativeOrAbsolute)) }
            };
            FriendControl stranger4 = new FriendControl()
            {
                UserID = 4,
                UserName = "陌生人4",
                CtrlType = friendCtrlTypeEnum.stranger,
                //CtrlBackGround = new SolidColorBrush(Colors.Red),
                //BtnExBackGround = new ImageBrush() { ImageSource = new BitmapImage(new Uri("/Qplus;component/Pic/icon_search_friends_item.png", UriKind.RelativeOrAbsolute)) }
            };
            searchLklst.AddLast(stranger1);
            searchLklst.AddLast(stranger2);
            searchLklst.AddLast(stranger3);
            searchLklst.AddLast(stranger4);
        }
        private void onlineListTest()
        {
            //var node = SearchData.Instance.UserList2["userList"].First;
            //int count = SearchData.Instance.UserList2.Count;
            //while (null != node)
            //{
            //    FriendControl frd = new FriendControl()
            //    {
            //        CtrlType = friendCtrlTypeEnum.stranger,
            //        UserID = (int)node["userID"],
            //        UserName = (string)node["userName"],
            //        UserLevel = (string)node["userLevel"],
            //        HeadType = (int)node["headType"],
            //        HeadValue = (string)node["headValue"]
            //    };
            //    onlineWP.Children.Add(frd);
            //    node = node.Next;
            //}
        }
        private void testBtn_Click(object sender, RoutedEventArgs e)
        {
            searchCtrl.nickName.Text = "searchCtrl.ActualHeight:" + searchCtrl.ActualHeight.ToString();

        }
#endregion
    }
}